package com.crm.business.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.*;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.poi.excel.BigExcelWriter;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CreateCache;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.crm.business.admin.mapper.AdminUserMapper;
import com.crm.business.admin.service.*;
import com.crm.business.auth.service.LoginService;
import com.crm.business.crm.service.CrmService;
import com.crm.business.crm.service.ICrmFieldService;
import com.crm.common.admin.common.AdminCodeEnum;
import com.crm.common.admin.common.AdminConst;
import com.crm.common.admin.entity.BO.*;
import com.crm.common.admin.entity.PO.*;
import com.crm.common.admin.entity.VO.AdminUserVO;
import com.crm.common.admin.entity.VO.HrmSimpleUserVO;
import com.crm.common.admin.entity.VO.UserBookVO;
import com.crm.common.constant.Constants;
import com.crm.common.core.redis.RedisCache;
import com.crm.common.crm.entity.PO.CrmField;
import com.crm.common.ka.core.common.BaseStatusEnum;
import com.crm.common.ka.core.common.Const;
import com.crm.common.ka.core.common.SystemCodeEnum;
import com.crm.common.ka.core.entity.BasePage;
import com.crm.common.ka.core.entity.UserInfo;
import com.crm.common.ka.core.exception.CrmException;
import com.crm.common.ka.core.feign.admin.entity.SimpleUser;
import com.crm.business.servlet.BaseServiceImpl;
import com.crm.common.ka.core.redis.Redis;
import com.crm.common.ka.core.utils.RecursionUtil;
import com.crm.common.ka.core.utils.TransferUtil;
import com.crm.business.utils.UserCacheUtil;
import com.crm.business.utils.UserUtil;
import com.crm.common.utils.StringUtils;
import com.crm.common.utils.spring.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author zhangzhiwei
 * @since 2020-04-27
 */
@Service
@Slf4j
public class AdminUserServiceImpl extends BaseServiceImpl<AdminUserMapper, AdminUser> implements IAdminUserService {

    @Autowired
    private IAdminRoleService adminRoleService;
    @Autowired
    private IAdminDeptService adminDeptService;
    @Autowired
    private IAdminUserConfigService adminUserConfigService;
    @Autowired
    private IAdminUserRoleService adminUserRoleService;
    @Autowired
    private IAdminAttentionService adminAttentionService;
    @Autowired
    private IAdminUserManageDeptService adminUserManageDeptService;

    @Resource
    private CrmService crmService;
    @Autowired
    private Redis redis;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private LoginService loginService;

    @CreateCache(name = Const.ADMIN_USER_NAME_CACHE_NAME, expire = 3, timeUnit = TimeUnit.DAYS)
    private Cache<Long, String> userCache;

    @Autowired
    private IAdminAddressBookService adminAddressBookService;

    @Override
    public List<Map<String, Object>> findByUsername(String username) {
        List<Map<String, Object>> userInfoList = getBaseMapper().findByUsername(username);
        userInfoList.forEach(userInfo -> {
            userInfo.put("superUserId", UserUtil.getSuperUser());
            userInfo.put("superRoleId", UserUtil.getSuperRole());
        });
        return userInfoList;
    }

    /**
     * 查询企业下所有用户
     *
     * @param adminUserBO 业务对象
     * @return ids
     */
    @Override
    public BasePage<AdminUserVO> queryUserList(AdminUserBO adminUserBO) {
        if (adminUserBO == null) {
            BasePage<AdminUserVO> userBasePage = new BasePage<>();
            userBasePage.setRecords(list().stream().map(adminUser -> {
                AdminUserVO userVO = BeanUtil.copyProperties(adminUser, AdminUserVO.class);
                userVO.setDeptName(UserCacheUtil.getDeptName(userVO.getDeptId()));
                return userVO;
            }).collect(Collectors.toList()));
            return userBasePage;
        }
        if (adminUserBO.getDeptId() != null) {
            List<Integer> list = adminDeptService.queryChildDept(adminUserBO.getDeptId());
            list.add(adminUserBO.getDeptId());
            adminUserBO.setDeptIdList(list);
        }
        BasePage<AdminUserVO> basePage = getBaseMapper().queryUserPage(adminUserBO.parse(), adminUserBO);
        List<AdminUserVO> userVOList = basePage.getRecords();
        if(CollectionUtil.isEmpty(userVOList)){
            return basePage;
        }
        List<Long> userIds = userVOList.stream().map(AdminUserVO::getUserId).collect(Collectors.toList());

        QueryWrapper<AdminUserRole> wrapper = new QueryWrapper<>();
        wrapper.in("user_id", userIds);
        List<AdminUserRole> userRoleIdList = adminUserRoleService.list(wrapper);

        QueryWrapper<AdminUserManageDept> manageDeptwrapper = new QueryWrapper<>();
        manageDeptwrapper.in("user_id", userIds);
        List<AdminUserManageDept> manageDeptIdList = adminUserManageDeptService.list(manageDeptwrapper);

        List<AdminRole> allRoleList =  adminRoleService.lambdaQuery().list();
        List<AdminDept> allDeptList =  adminDeptService.lambdaQuery().list();

        basePage.getRecords().forEach(adminUserVO -> {
            Long userId = adminUserVO.getUserId();
            if(CollectionUtil.isNotEmpty(userRoleIdList)){
                List<AdminUserRole> userRoles = userRoleIdList.stream().filter(userRole -> userRole.getUserId().equals(userId)).collect(Collectors.toList());
                if(CollectionUtil.isNotEmpty(userRoles)){
                    List<Integer> roleIds = userRoles.stream().map(AdminUserRole::getRoleId).collect(Collectors.toList());
                    List<AdminRole> adminRoleList = allRoleList.stream().filter(role -> roleIds.contains(role.getRoleId())).collect(Collectors.toList());
                    adminUserVO.setRoleId(adminRoleList.stream().map(adminRole -> adminRole.getRoleId().toString()).collect(Collectors.joining(",")));
                    adminUserVO.setRoleName(adminRoleList.stream().map(AdminRole::getRoleName).collect(Collectors.joining(",")));
                }
            }

            if(CollectionUtil.isNotEmpty(manageDeptIdList)){
                List<AdminUserManageDept> manageDepts = manageDeptIdList.stream().filter(manageDept -> manageDept.getUserId().equals(userId)).collect(Collectors.toList());
                if(CollectionUtil.isNotEmpty(manageDepts)){
                    List<Integer> deptIds = manageDepts.stream().map(AdminUserManageDept::getDeptId).collect(Collectors.toList());
                    List<AdminDept> manageDeptList  = allDeptList.stream().filter(dept -> deptIds.contains(dept.getDeptId())).collect(Collectors.toList());
                    adminUserVO.setManageDeptId(manageDeptList.stream().map(adminDept -> adminDept.getDeptId().toString()).collect(Collectors.joining(",")));
                    adminUserVO.setManageDeptName(manageDeptList.stream().map(AdminDept::getName).collect(Collectors.joining(",")));
                }
            }
        });
        return basePage;
    }

    /**
     * 查询企业下所有用户基本信息
     *
     * @param adminUserBO 业务对象
     * @return ids
     */
    @Override
    public BasePage<AdminUserVO> queryBaseUserList(AdminUserBO adminUserBO) {
        if (adminUserBO == null) {
            BasePage<AdminUserVO> userBasePage = new BasePage<>();
            userBasePage.setRecords(list().stream().map(adminUser -> {
                AdminUserVO userVO = BeanUtil.copyProperties(adminUser, AdminUserVO.class);
                userVO.setDeptName(UserCacheUtil.getDeptName(userVO.getDeptId()));
                return userVO;
            }).collect(Collectors.toList()));
            return userBasePage;
        }
        if (adminUserBO.getDeptId() != null) {
            List<Integer> list = adminDeptService.queryChildDept(adminUserBO.getDeptId());
            list.add(adminUserBO.getDeptId());
            adminUserBO.setDeptIdList(list);
        }
        BasePage<AdminUserVO> basePage = getBaseMapper().queryUserPage(adminUserBO.parse(), adminUserBO);
        return basePage;
    }

    /**
     * 查询企业下所有用户基本信息
     *
     * @param adminUserBO 业务对象
     * @return ids
     */
    @Override
    public List<AdminUserVO> queryBaseUserVoList(AdminUserBO adminUserBO) {
        if (adminUserBO == null) {
            return list().stream().map(adminUser -> {
                AdminUserVO userVO = BeanUtil.copyProperties(adminUser, AdminUserVO.class);
                userVO.setDeptName(UserCacheUtil.getDeptName(userVO.getDeptId()));
                return userVO;
            }).collect(Collectors.toList());
        }
        if (adminUserBO.getDeptId() != null) {
            List<Integer> list = adminDeptService.queryChildDept(adminUserBO.getDeptId());
            list.add(adminUserBO.getDeptId());
            adminUserBO.setDeptIdList(list);
        }
        List<AdminUserVO> list = getBaseMapper().queryUserList( adminUserBO);
        return list;
    }



    /**
     * 查询该用户下级的用户
     *
     * @param userId 用户ID 0代表全部
     * @return data
     */
    @Override
    public List<Long> queryChildUserId(Long userId) {
        return RecursionUtil.getChildList(list(), "parentId", userId, "userId", "userId");
    }

    /**
     * 新增或修改用户
     *
     * @param adminUserVO data
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setUser(AdminUserVO adminUserVO) {
        String lockkey = Constants.SET_USER + adminUserVO.getUserId();
        String value = UUID.randomUUID().toString();
        boolean result = redis.lock(lockkey, value, 10, TimeUnit.SECONDS);
        if (!result) {
            throw new CrmException(SystemCodeEnum.SYSTEM_BAD_REQUEST);
        }
        try{
            if (adminUserVO.getParentId() == null) {
                adminUserVO.setParentId(0L);
            }
            if (!UserUtil.isAdmin() && adminUserVO.getParentId() == 0) {
                throw new CrmException(AdminCodeEnum.ADMIN_PARENT_USER_NOTNULL_ERROR);
            }
            List<Long> userList = queryChildUserId(adminUserVO.getUserId());
            if (userList.contains(adminUserVO.getParentId())) {
                throw new CrmException(AdminCodeEnum.ADMIN_PARENT_USER_ERROR);
            }
            if (adminUserVO.getUserId().equals(adminUserVO.getParentId())) {
                throw new CrmException(AdminCodeEnum.ADMIN_PARENT_USER_ERROR1);
            }
            Integer realcount = query().eq("realname", adminUserVO.getRealname()).ne("user_id",adminUserVO.getUserId()).count();
            if (realcount > 0) {
                throw new CrmException(AdminCodeEnum.ADMIN_USER_REAL_NAME_EXIST_ERROR);
            }
            //不修改用户名
            adminUserVO.setUsername(null);
            //不修改密码
            adminUserVO.setPassword(null);

            AdminUser oldUser = this.getBaseMapper().selectById(adminUserVO.getUserId());
            if(UserUtil.getSuperUser().equals(adminUserVO.getUserId())){
                throw new CrmException(AdminCodeEnum.ADMIN_USER_EDIT_ERROR);
            }

//            if(!oldUser.getStatus().equals(adminUserVO.getStatus())){
//                BillGroup billGroup = SpringUtils.getBean(BillGroupService.class).queryBillGroup(OrgIdThreadLocal.getOrgId());
//                if(!CrmBusinessEnum.PublicEnum.ONE.getType().equals(billGroup.getStatus())){
//                    throw new CrmException(AuthorizationCodeEnum.AUTHORIZATION_ACCOUNT_DISABLE);
//                }
//                Date now = DateUtils.getNowDate();
//                if(now.before(billGroup.getOpenStartTime()) || now.after(billGroup.getOpenEndTime())){
//                    throw new CrmException(AuthorizationCodeEnum.AUTHORIZATION_ACCOUNT_EXPIRE);
//                }
//                if (BaseStatusEnum.CLOSE.getStatus().equals(adminUserVO.getStatus())) {
//                    Long seatsId =  getBaseMapper().getBindSeatsId(OrgIdThreadLocal.getOrgId(),adminUserVO.getUserId(),null);
//                    if(!Optional.ofNullable(seatsId).isPresent()){
//                        throw new CrmException(AdminCodeEnum.ADMIN_USER_SEATS_UNBIND_ERROR);
//                    }
//                    int i = getBaseMapper().unBindSeats(adminUserVO.getUserId(),seatsId,OrgIdThreadLocal.getOrgId());
//                    if(i <= 0){
//                        throw new CrmException(AdminCodeEnum.ADMIN_USER_SEATS_UNBIND_ERROR);
//                    }
//                } else if (BaseStatusEnum.OPEN.getStatus().equals(adminUserVO.getStatus())) {
//                    Long seatsId =  getBaseMapper().getOneSeats(OrgIdThreadLocal.getOrgId(), DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,new Date()));
//                    if(!Optional.ofNullable(seatsId).isPresent()){
//                        throw new CrmException(AdminCodeEnum.ADMIN_USER_GET_SEATS_ERROR);
//                    }
//                    int i =  getBaseMapper().bindSeats(adminUserVO.getUserId(),seatsId,OrgIdThreadLocal.getOrgId(), DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,new Date()));
//                    if(i <= 0){
//                        throw new CrmException(AdminCodeEnum.ADMIN_USER_SEATS_BIND_ERROR);
//                    }
//                }
//            }

            AdminUser adminUser = BeanUtil.copyProperties(adminUserVO, AdminUser.class);
            adminUserRoleService.saveByUserId(adminUserVO.getUserId(), true, StrUtil.splitTrim(adminUserVO.getRoleId(), Const.SEPARATOR));
            adminUserManageDeptService.saveByUserId(adminUserVO.getUserId(), true, StrUtil.splitTrim(adminUserVO.getManageDeptId(), Const.SEPARATOR));
            updateById(adminUser);
            crmService.batchUpdateEsData(adminUser.getUserId().toString(), adminUser.getRealname());
            Long key = adminUser.getUserId();
            userCache.put(key, adminUser.getRealname());
            SpringUtils.getBean(IAdminUserService.class).saveUserDeptCache();
            loginService.updateLoginUserInfo(Arrays.asList(new Long[]{adminUserVO.getUserId()}));
        }finally {
            redis.unlock(lockkey,value);
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addUser(AdminUserVO adminUser) {
        String lockkey = Constants.ADD_USER + adminUser.getUsername();
        String value = UUID.randomUUID().toString();
        boolean result = redis.lock(lockkey, value, 10, TimeUnit.SECONDS);
        if (!result) {
            throw new CrmException(SystemCodeEnum.SYSTEM_BAD_REQUEST);
        }
        try{
            if (adminUser.getParentId() == null) {
                adminUser.setParentId(0L);
            }
            if (!UserUtil.isAdmin() && adminUser.getParentId() == 0) {
                throw new CrmException(AdminCodeEnum.ADMIN_PARENT_USER_NOTNULL_ERROR);
            }
            if (!ReUtil.isMatch(AdminConst.DEFAULT_PASSWORD_INTENSITY, adminUser.getPassword())) {
                throw new CrmException(AdminCodeEnum.ADMIN_PASSWORD_INTENSITY_ERROR);
            }
            Integer count = query().eq("username", adminUser.getUsername()).count();
            if (count > 0) {
                throw new CrmException(AdminCodeEnum.ADMIN_USER_EXIST_ERROR);
            }
            Integer realcount = query().eq("realname", adminUser.getRealname()).count();
            if (realcount > 0) {
                throw new CrmException(AdminCodeEnum.ADMIN_USER_REAL_NAME_EXIST_ERROR);
            }
            String salt = IdUtil.fastSimpleUUID();
            AdminUser adminUserPO = BeanUtil.copyProperties(adminUser, AdminUser.class);
            adminUserPO.setCreateTime(new Date());
            adminUserPO.setNum(RandomUtil.randomNumbers(15));
            adminUserPO.setMobile(adminUserPO.getUsername());
            adminUserPO.setSalt(salt);
            adminUserPO.setPassword(UserUtil.sign((adminUser.getUsername().trim() + adminUser.getPassword().trim()), salt));
            save(adminUserPO);
//            if (BaseStatusEnum.OPEN.getStatus().equals(adminUserPO.getStatus())) {
//                BillGroup billGroup = SpringUtils.getBean(BillGroupService.class).queryBillGroup(OrgIdThreadLocal.getOrgId());
//                if(!CrmBusinessEnum.PublicEnum.ONE.getType().equals(billGroup.getStatus())){
//                    throw new CrmException(AuthorizationCodeEnum.AUTHORIZATION_ACCOUNT_DISABLE);
//                }
//                Date now = DateUtils.getNowDate();
//                if(now.before(billGroup.getOpenStartTime()) || now.after(billGroup.getOpenEndTime())){
//                    throw new CrmException(AuthorizationCodeEnum.AUTHORIZATION_ACCOUNT_EXPIRE);
//                }
//                Long seatsId =  getBaseMapper().getOneSeats(OrgIdThreadLocal.getOrgId(), DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,new Date()));
//                if(!Optional.ofNullable(seatsId).isPresent()){
//                    throw new CrmException(AdminCodeEnum.ADMIN_USER_GET_SEATS_ERROR);
//                }
//                int i =  getBaseMapper().bindSeats(adminUserPO.getUserId(),seatsId,OrgIdThreadLocal.getOrgId(), DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,new Date()));
//                if(i <= 0){
//                    throw new CrmException(AdminCodeEnum.ADMIN_USER_SEATS_BIND_ERROR);
//                }
//            }
            adminUserConfigService.initUserConfig(adminUserPO.getUserId());
            adminUserRoleService.saveByUserId(adminUserPO.getUserId(), false, StrUtil.splitTrim(adminUser.getRoleId(), Const.SEPARATOR));
            adminUserManageDeptService.saveByUserId(adminUserPO.getUserId(), true, StrUtil.splitTrim(adminUser.getManageDeptId(), Const.SEPARATOR));
            Long key = adminUserPO.getUserId();
            userCache.put(key, adminUserPO.getRealname());
            SpringUtils.getBean(IAdminUserService.class).saveUserDeptCache();
        }finally {
            redis.unlock(lockkey,value);
        }
    }

    /**
     * 修改用户信息
     *
     * @param adminUser
     */
    @Override
    public void updateUser(AdminUser adminUser) {
//        if (!UserUtil.getUser().getUsername().equals(adminUser.getUsername())) {
//            throw new CrmException(AdminCodeEnum.ADMIN_USERNAME_EDIT_ERROR);
//        }
        AdminUser oldUser = getById(adminUser.getUserId());
        log.info("UserUtil.getUser():" + JSONObject.toJSONString(UserUtil.getUser()));
        if(Optional.ofNullable(adminUser.getUsername()).isPresent()){
            adminUser.setUsername(null);
        }
        adminUser.setUserId(UserUtil.getUserId());
        boolean b = false;
        if (StrUtil.isNotEmpty(adminUser.getPassword())) {
            if (!ReUtil.isMatch(AdminConst.DEFAULT_PASSWORD_INTENSITY, adminUser.getPassword())) {
                throw new CrmException(AdminCodeEnum.ADMIN_PASSWORD_INTENSITY_ERROR);
            }
            b = true;
            adminUser.setSalt(IdUtil.simpleUUID());
            adminUser.setPassword(UserUtil.sign((oldUser.getUsername().trim() + adminUser.getPassword().trim()), adminUser.getSalt()));
        }
        boolean update = updateById(adminUser);

        // 校验通讯录更新
        if(StringUtils.isNotEmpty(adminUser.getWechat()) || StringUtils.isNotEmpty(adminUser.getWechatCodeUrl())){
            AdminAddressBook addressBook = adminAddressBookService.queryAddressBookByUserId(UserUtil.getUserId());
            if(ObjectUtil.isNotEmpty(addressBook)){
                addressBook.setWechat(adminUser.getWechat());
                addressBook.setWechatCodeUrl(adminUser.getWechatCodeUrl());
                addressBook.setWechatDownUrl(adminUser.getWechatDownUrl());
                addressBook.setUpdateTime(new Date());
                adminAddressBookService.updateById(addressBook);
            }
        }
        SpringUtils.getBean(IAdminUserService.class).saveUserDeptCache();
        crmService.batchUpdateEsData(adminUser.getUserId().toString(), adminUser.getRealname());
        if (b && update) {
            UserUtil.userExit(adminUser.getUserId(), null);
        }
    }

    /**
     * 修改用户账号功能
     *
     * @param id       用户ID
     * @param username 新的用户名
     * @param password 新的密码
     * @return 操作状态
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer usernameEdit(Integer id, String username, String password) {
        if (!ReUtil.isMatch(AdminConst.DEFAULT_PASSWORD_INTENSITY, password)) {
            throw new CrmException(AdminCodeEnum.ADMIN_PASSWORD_INTENSITY_ERROR);
        }
        AdminUser adminUser = getById(id);
        if (adminUser == null) {
            throw new CrmException(AdminCodeEnum.ADMIN_USER_NOT_EXIST_ERROR);
        }
        if (adminUser.getUsername().equals(username)) {
            throw new CrmException(AdminCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        Integer count = lambdaQuery().eq(AdminUser::getUsername, username).count();
        if (count > 0) {
            throw new CrmException(AdminCodeEnum.ADMIN_PHONE_REGISTER_ERROR);
        }
        adminUser.setUsername(username);
        adminUser.setMobile(username);
        adminUser.setPassword(UserUtil.sign(username + password, adminUser.getSalt()));
        UserUtil.userExit(adminUser.getUserId(), null);
        updateById(adminUser);
        return null;
    }

    /**
     * excel导入员工
     *
     * @param file file
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject excelImport(MultipartFile file) {
        List<List<Object>> errList = new ArrayList<>();
        String filePath = getFilePath(file);
        AtomicReference<Integer> num = new AtomicReference<>(0);
        ExcelUtil.readBySax(filePath, 0, (int sheetIndex, int rowIndex, List<Object> rowList) -> {
            if (rowIndex > 1) {
                num.getAndSet(num.get() + 1);
                if (StrUtil.isEmptyIfStr(rowList.get(0))) {
                    rowList.add(0, "用户名不能为空");
                    errList.add(rowList);
                    return;
                }
                if (StrUtil.isEmptyIfStr(rowList.get(1))) {
                    rowList.add(0, "密码不能为空");
                    errList.add(rowList);
                    return;
                }
                if (!ReUtil.isMatch("^(?=.*[a-zA-Z])(?=.*\\d).{6,20}$", rowList.get(1).toString())) {
                    rowList.add(0, "密码必须由 6-20位字母、数字组成");
                    errList.add(rowList);
                    return;
                }
                if (StrUtil.isEmptyIfStr(rowList.get(2))) {
                    rowList.add(0, "姓名不能为空");
                    errList.add(rowList);
                    return;
                }
                String username = rowList.get(0).toString().trim();
                Integer count = lambdaQuery().eq(AdminUser::getUsername, username).count();
                if (count > 0) {
                    rowList.add(0, "手机号已存在");
                    errList.add(rowList);
                    return;
                }
                if (!ReUtil.isMatch("^[1][3,4,5,6,7,8,9][0-9]{9}$", username)) {
                    rowList.add(0, "手机号格式不正确");
                    errList.add(rowList);
                    return;
                }
                String password = rowList.get(1).toString().trim();
                String realname = rowList.get(2).toString().trim();
                Integer realcount = lambdaQuery().eq(AdminUser::getRealname, realname).count();
                if (count > 0) {
                    rowList.add(0, "用户真实姓名已存在");
                    errList.add(rowList);
                    return;
                }
                String sex = Optional.ofNullable(rowList.get(3)).orElse("").toString().trim();
                String email = Optional.ofNullable(rowList.get(4)).orElse("").toString().trim();
                String post = Optional.ofNullable(rowList.get(5)).orElse("").toString().trim();
                AdminUser adminUser = new AdminUser();
                String salt = IdUtil.fastSimpleUUID();
                adminUser.setUsername(username);
                adminUser.setPassword(UserUtil.sign((adminUser.getUsername().trim() + password.trim()), salt));
                adminUser.setSalt(salt);
                adminUser.setNum(RandomUtil.randomNumbers(15));
                adminUser.setCreateTime(new Date());
                adminUser.setRealname(realname);
                adminUser.setMobile(username);
                adminUser.setEmail(email);
                adminUser.setPost(post);
                adminUser.setStatus(0);
                if (StrUtil.isNotEmpty(sex)) {
                    if ("女".equals(sex)) {
                        adminUser.setSex(2);
                    } else {
                        adminUser.setSex(1);
                    }
                }
                save(adminUser);
                adminUserConfigService.initUserConfig(UserUtil.getUserId());
            }
        });
        FileUtil.del(filePath);
        JSONObject result = new JSONObject().fluentPut("totalSize", num.get()).fluentPut("errSize", 0);
        if (errList.size() > 0) {
            BigExcelWriter writer = null;
            try {
                String token = IdUtil.simpleUUID();
                writer = ExcelUtil.getBigWriter(FileUtil.getTmpDirPath() + "/" + token);
                writer.merge(6, "系统用户导入模板(*)为必填项");
                for (int i = 0; i < 7; i++) {
                    writer.setColumnWidth(i, 20);
                }
                writer.setDefaultRowHeight(20);
                Cell cell = writer.getCell(0, 0);
                CellStyle cellStyle = cell.getCellStyle();
                cellStyle.setFillForegroundColor(IndexedColors.SKY_BLUE.getIndex());
                cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                Font font = writer.createFont();
                font.setBold(true);
                font.setFontHeightInPoints((short) 16);
                cellStyle.setFont(font);
                cell.setCellStyle(cellStyle);
                writer.writeHeadRow(Arrays.asList("错误信息", "手机号(*)", "登录密码(*)", "姓名(*)", "性别", "邮箱", "岗位"));
                writer.write(errList);
                result.fluentPut("errSize", errList.size()).fluentPut("token", token);
            } finally {
                if (writer != null) {
                    writer.close();
                }
            }
        }
        return result;
    }

    private String getFilePath(MultipartFile file) {
        String dirPath = FileUtil.getTmpDirPath();
        try {
            InputStream inputStream = file.getInputStream();
            File fromStream = FileUtil.writeFromStream(inputStream, dirPath + "/" + IdUtil.simpleUUID() + file.getOriginalFilename());
            return fromStream.getAbsolutePath();
        } catch (IOException e) {
            throw new CrmException(SystemCodeEnum.SYSTEM_UPLOAD_FILE_ERROR);
        }
    }

    /**
     * 设置状态
     *
     * @param adminUserStatusBO status
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void setUserStatus(AdminUserStatusBO adminUserStatusBO) {
//        BillGroup billGroup = SpringUtils.getBean(BillGroupService.class).queryBillGroup(OrgIdThreadLocal.getOrgId());
//        if(!CrmBusinessEnum.PublicEnum.ONE.getType().equals(billGroup.getStatus())){
//            throw new CrmException(AuthorizationCodeEnum.AUTHORIZATION_ACCOUNT_DISABLE);
//        }
//        Date now = DateUtils.getNowDate();
//        if(now.before(billGroup.getOpenStartTime()) || now.after(billGroup.getOpenEndTime())){
//            throw new CrmException(AuthorizationCodeEnum.AUTHORIZATION_ACCOUNT_EXPIRE);
//        }

        for (Long id : adminUserStatusBO.getIds()){
            if(UserUtil.getSuperUser().equals(id)){
                throw new CrmException(AdminCodeEnum.ADMIN_USER_CHECK_ERROR);
            }
        }

        for (Long id : adminUserStatusBO.getIds()) {
            String lockkey = Constants.SET_USER + id;
            String value = UUID.randomUUID().toString();
            boolean result = redis.lock(lockkey, value, 10, TimeUnit.SECONDS);
            if (!result) {
                throw new CrmException(SystemCodeEnum.SYSTEM_BAD_REQUEST);
            }
            try {
                AdminUser adminUser = this.getBaseMapper().selectById(id);
                if(adminUser.getStatus().equals(adminUserStatusBO.getStatus())){
                    continue;
                }
                if (BaseStatusEnum.CLOSE.getStatus().equals(adminUserStatusBO.getStatus())) {
                    if (id.equals(UserUtil.getSuperUser())) {
                        throw new CrmException(AdminCodeEnum.ADMIN_SUPER_USER_DISABLED_ERROR);
                    }
                    UserUtil.userExit(id, null);
//                    Long seatsId =  getBaseMapper().getBindSeatsId(OrgIdThreadLocal.getOrgId(),id,null);
//                    if(!Optional.ofNullable(seatsId).isPresent()){
//                        throw new CrmException(AdminCodeEnum.ADMIN_USER_SEATS_UNBIND_ERROR);
//                    }
//                    int i = getBaseMapper().unBindSeats(id,seatsId,OrgIdThreadLocal.getOrgId());
//                    if(i <= 0){
//                        throw new CrmException(AdminCodeEnum.ADMIN_USER_SEATS_UNBIND_ERROR);
//                    }
                } else if (BaseStatusEnum.OPEN.getStatus().equals(adminUserStatusBO.getStatus())) {
                    Integer roleCount = adminUserRoleService.lambdaQuery().eq(AdminUserRole::getUserId, id).count();
                    if (roleCount == 0) {
                        throw new CrmException(AdminCodeEnum.ADMIN_USER_NOT_ROLE_ERROR);
                    }
//                    AdminUser adminUser = getById(id);
                    if (adminUser.getDeptId() == null) {
                        throw new CrmException(AdminCodeEnum.ADMIN_USER_NOT_DEPT_ERROR);
                    }
                    if (adminUser.getParentId() == null || adminUser.getParentId() == 0) {
                        throw new CrmException(AdminCodeEnum.ADMIN_USER_NOT_PARENT_ERROR);
                    }
//                    Long seatsId =  getBaseMapper().getOneSeats(OrgIdThreadLocal.getOrgId(), DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,new Date()));
//                    if(!Optional.ofNullable(seatsId).isPresent()){
//                        throw new CrmException(AdminCodeEnum.ADMIN_USER_GET_SEATS_ERROR);
//                    }
//                    int i =  getBaseMapper().bindSeats(id,seatsId,OrgIdThreadLocal.getOrgId(), DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,new Date()));
//                    if(i <= 0){
//                        throw new CrmException(AdminCodeEnum.ADMIN_USER_SEATS_BIND_ERROR);
//                    }
                }
                lambdaUpdate().set(AdminUser::getStatus, adminUserStatusBO.getStatus()).eq(AdminUser::getUserId, id).update();
                SpringUtils.getBean(IAdminUserService.class).saveUserDeptCache();
            }finally {
                redis.unlock(lockkey,value);
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void resetPassword(AdminUserStatusBO adminUserStatusBO) {
        for (Long id : adminUserStatusBO.getIds()){
            if(UserUtil.getSuperUser().equals(id)){
                throw new CrmException(AdminCodeEnum.ADMIN_USER_CHECK_ERROR);
            }
        }

        if (!ReUtil.isMatch(AdminConst.DEFAULT_PASSWORD_INTENSITY, adminUserStatusBO.getPassword())) {
            throw new CrmException(AdminCodeEnum.ADMIN_PASSWORD_INTENSITY_ERROR);
        }
        for (Long id : adminUserStatusBO.getIds()) {
            AdminUser adminUser = getById(id);
            String password = UserUtil.sign(adminUser.getUsername() + adminUserStatusBO.getPassword(), adminUser.getSalt());
            lambdaUpdate().set(AdminUser::getPassword, password).eq(AdminUser::getUserId, id).update();
            UserUtil.userExit(adminUser.getUserId(), null);
        }
    }

    /**
     * 根据用户ID查询角色ID
     *
     * @param userId userId
     * @return ids
     */
    @Override
    public List<Integer> queryUserRoleIds(Long userId) {
        QueryWrapper<AdminUserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("role_id").eq("user_id", userId);
        return adminUserRoleService.listObjs(queryWrapper, obj -> Integer.valueOf(obj.toString()));
    }

    /**
     * 递归查询该用户下级的用户
     */
    private List<Long> queryChildUserId(List<AdminUser> userList, Long parentId, int depth) {
        depth--;
        List<Long> arrList = new ArrayList<>();
        if (depth < 0) {
            return arrList;
        }
        for (AdminUser adminUser : userList) {
            if (Objects.equals(parentId, adminUser.getParentId())) {
                arrList.add(adminUser.getUserId());
                arrList.addAll(queryChildUserId(userList, adminUser.getUserId(), depth));
            }
        }
        return arrList;
    }

    /**
     * 通讯录查询
     *
     * @param userBookBO data
     * @return
     */
    @Override
    public BasePage<UserBookVO> queryListName(UserBookBO userBookBO) {
        userBookBO.setUserId(UserUtil.getUserId());
        return getBaseMapper().queryListName(userBookBO.parse(), userBookBO);
    }

    /**
     * 切换关注状态
     *
     * @param userId 用户ID 0代表全部
     * @return
     */
    @Override
    public void attention(Long userId) {
        QueryWrapper<AdminAttention> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("be_user_id", userId);
        int count = adminAttentionService.count(queryWrapper);
        if (count > 0) {
            adminAttentionService.remove(queryWrapper);
        } else {
            AdminAttention attention = new AdminAttention();
            attention.setBeUserId(userId);
            attention.setAttentionUserId(UserUtil.getUserId());
            adminAttentionService.save(attention);
        }
    }

    /**
     * 通过用户ID查询用户昵称
     *
     * @param userId 用户ID
     * @return data
     */
    @Override
    public String getNameByUserId(Long userId) {
        String name = userCache.get(userId);
        if (name != null) {
            return name;
        }
        AdminUser adminUser = query().select("realname").eq("user_id", userId).one();
        if (adminUser == null) {
            return "";
        }
        userCache.put(userId, adminUser.getRealname());
        return adminUser.getRealname();
    }

    /**
     * 根据ids查询用户信息
     *
     * @param ids id列表
     * @return data
     */
    @Override
    public List<SimpleUser> queryUserByIds(List<Long> ids) {
        if (ids.size() == 0) {
            return new ArrayList<>();
        }
        LambdaQueryWrapper<AdminUser> queryWrapper = new LambdaQueryWrapper<>();
        String idStr = ids.stream().map(String::valueOf).collect(Collectors.joining(Const.SEPARATOR));
        queryWrapper.select(AdminUser::getUserId, AdminUser::getImg, AdminUser::getRealname).in(AdminUser::getUserId, ids)
                .last(" ORDER BY instr('," + idStr + ",',CONCAT(',',user_id,','))");
        List<AdminUser> list = list(queryWrapper);
        return list.stream().map(obj -> BeanUtil.copyProperties(obj, SimpleUser.class)).collect(Collectors.toList());
    }

    @Override
    public List<Long> queryNormalUserByIds(List<Long> ids) {
        List<Long> userIdList = new ArrayList<>();
        if (ids.size() == 0) {
            return userIdList;
        }
        LambdaQueryWrapper<AdminUser> queryWrapper = new LambdaQueryWrapper<>();
        String idStr = ids.stream().map(String::valueOf).collect(Collectors.joining(Const.SEPARATOR));
        queryWrapper.select(AdminUser::getUserId, AdminUser::getImg, AdminUser::getRealname)
                .in(AdminUser::getUserId, ids)
                .eq(AdminUser::getStatus, 1)
                .last(" ORDER BY instr('," + idStr + ",',CONCAT(',',user_id,','))");
        List<AdminUser> list = list(queryWrapper);
        if (CollUtil.isNotEmpty(list)) {
            userIdList = list.stream().map(AdminUser::getUserId).collect(Collectors.toList());
        }
        return userIdList;
    }

    /**
     * 根据部门ids查询有效用户列表
     *
     * @param ids id列表
     * @return data
     */
    @Override
    public List<Long> queryNormalUserByDeptIds(List<Integer> ids) {
        if (ids.size() == 0) {
            return new ArrayList<>();
        }
        LambdaQueryWrapper<AdminUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(AdminUser::getUserId).in(AdminUser::getDeptId, ids).eq(AdminUser::getStatus, 1);
        return listObjs(queryWrapper, obj -> Long.valueOf(obj.toString()));
    }

    /**
     * 根据部门ids查询用户列表
     *
     * @param ids id列表
     * @return data
     */
    @Override
    public List<Long> queryUserByDeptIds(List<Integer> ids) {
        if (ids.size() == 0) {
            return new ArrayList<>();
        }
        LambdaQueryWrapper<AdminUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(AdminUser::getUserId).in(AdminUser::getDeptId, ids);
        return listObjs(queryWrapper, obj -> Long.valueOf(obj.toString()));
    }

    /**
     * 根据部门ids查询用户列表
     *
     * @param ids id列表
     * @return data
     */
    @Override
    public List<Long> queryEnableUserByDeptIds(List<Integer> ids) {
        if (ids.size() == 0) {
            return new ArrayList<>();
        }
        LambdaQueryWrapper<AdminUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(AdminUser::getUserId).in(AdminUser::getDeptId, ids).ne(AdminUser::getStatus,0);
        return listObjs(queryWrapper, obj -> Long.valueOf(obj.toString()));
    }



    @Override
    public DeptUserListVO queryDeptUserList(Integer deptId, boolean isAllUser) {
        DeptUserListVO deptUserListVO = new DeptUserListVO();
        List<DeptVO> deptList = adminDeptService.queryDeptUserList();
        createTree(deptId, deptList);
        List<HrmSimpleUserVO> userList;
        if (isAllUser) {
            userList = getBaseMapper().querySimpleUserByDeptId(deptId);
        } else {
            userList = getBaseMapper().querySimpleUserByDeptIdAndExamine(deptId);
        }
        List<DeptVO> collect = deptList.stream().filter(dept -> dept.getPid().equals(deptId)).collect(Collectors.toList());
        deptUserListVO.setDeptList(collect);
        deptUserListVO.setUserList(userList);
        return deptUserListVO;
    }

    private List<DeptVO> createTree(int pid, List<DeptVO> deptList) {
        List<DeptVO> treeDept = new ArrayList<>();
        for (DeptVO dept : deptList) {
            if (pid == dept.getPid()) {
                treeDept.add(dept);
                List<DeptVO> children = createTree(dept.getDeptId(), deptList);
                if (CollUtil.isNotEmpty(children)) {
                    for (DeptVO child : children) {
                        dept.setAllNum(dept.getAllNum() + child.getAllNum());
                    }
                    dept.setHasChildren(1);
                } else {
                    dept.setHasChildren(0);
                }
            }
        }
        return treeDept;
    }

    @Override
    public Set<HrmSimpleUserVO> queryDeptUserListByHrm(DeptUserListByHrmBO deptUserListByHrmBO) {
        Set<HrmSimpleUserVO> userVOSet = new HashSet<>();
        if (CollUtil.isNotEmpty(deptUserListByHrmBO.getDeptIdList())) {
            List<AdminUser> userList = findChildUserList(deptUserListByHrmBO.getDeptIdList());
            List<HrmSimpleUserVO> hrmSimpleUserVOS = TransferUtil.transferList(userList, HrmSimpleUserVO.class);
            userVOSet.addAll(hrmSimpleUserVOS);
        }
        if (CollUtil.isNotEmpty(deptUserListByHrmBO.getUserIdList())) {
            List<AdminUser> userList = query().select("user_id", "realname", "img", "sex", "username as mobile", "post").in("user_id", deptUserListByHrmBO.getUserIdList())
                    .ne("status", 0).list();
            List<HrmSimpleUserVO> hrmSimpleUserVOS = TransferUtil.transferList(userList, HrmSimpleUserVO.class);
            userVOSet.addAll(hrmSimpleUserVOS);
        }
        return userVOSet;
    }

    private List<AdminUser> findChildUserList(List<Integer> deptIds) {
        List<AdminUser> empList = new ArrayList<>();
        for (Integer deptId : deptIds) {
            List<AdminUser> list = query().select("user_id", "realname", "img", "sex", "username as mobile", "post").eq("dept_id", deptId).ne("status", 0).list();
            empList.addAll(list);
            List<AdminDept> childList = adminDeptService.lambdaQuery().select(AdminDept::getDeptId).eq(AdminDept::getPid, deptId).list();
            if (CollUtil.isNotEmpty(childList)) {
                List<Integer> childDeptIds = childList.stream().map(AdminDept::getDeptId).collect(Collectors.toList());
                empList.addAll(findChildUserList(childDeptIds));
            }
        }
        return empList;
    }

    @Override
    public List<Long> queryUserIdByRealName(List<String> realNames) {
        if (CollUtil.isEmpty(realNames)) {
            return new ArrayList<>();
        }
        return lambdaQuery().select(AdminUser::getUserId)
                .in(AdminUser::getRealname, realNames)
                .list().stream().map(AdminUser::getUserId).collect(Collectors.toList());
    }

    @Override
    public UserInfo queryLoginUserInfo(Long userId) {
        UserInfo userInfo = getBaseMapper().queryLoginUserInfo(userId);
//        userInfo.setSuperUserId(UserUtil.getSuperUser());
//        AdminRole role = adminRoleService.lambdaQuery().eq(AdminRole::getRemark, "admin").last(" limit 1").one();
//        userInfo.setSuperRoleId(role.getRoleId());
        userInfo.setRoles(queryUserRoleIds(userInfo.getUserId()));
        return userInfo;
    }

    /**
     * 查询当前系统有没有初始化
     *
     * @return data
     */
    @Override
    public Integer querySystemStatus() {
        Integer count = lambdaQuery().count();
        return count > 0 ? 1 : 0;
    }

    /**
     * 系统用户初始化
     */
    @Override
    public void initUser(SystemUserBO systemUserBO) {
        Integer integer = querySystemStatus();
        if (integer > 0) {
            return;
        }
        String md5 = SecureUtil.md5(systemUserBO.getUsername());
        String mobile = systemUserBO.getUsername();
        String proCode = mobile.substring(mobile.length() - 6);
        StringBuilder code = new StringBuilder();
        for (Character c : proCode.toCharArray()) {
            code.append(md5.charAt(Integer.valueOf(c.toString())));
        }
        if (!code.toString().equals(systemUserBO.getCode())) {
            throw new CrmException(AdminCodeEnum.ADMIN_PHONE_CODE_ERROR);
        }
        AdminUser adminUser = new AdminUser();
        adminUser.setUsername(systemUserBO.getUsername());
        adminUser.setSalt(IdUtil.simpleUUID());
        adminUser.setPassword(UserUtil.sign(systemUserBO.getUsername() + systemUserBO.getPassword(), adminUser.getSalt()));
        adminUser.setCreateTime(new Date());
        adminUser.setRealname("admin");
        adminUser.setMobile(systemUserBO.getUsername());
        adminUser.setDeptId(14852);
        adminUser.setPost("标准岗位");
        adminUser.setStatus(1);
        adminUser.setParentId(0L);
        save(adminUser);
        lambdaUpdate().set(AdminUser::getUserId, UserUtil.getSuperUser())
                .eq(AdminUser::getUserId, adminUser.getUserId()).update();
//        registerSeataToNacos();
    }

//    @Value("${seata.config.nacos.serverAddr}")
    private String serverAddr;

    @Autowired
    private DataSourceProperties dataSourceProperties;

//    private void registerSeataToNacos() {
//        Map<String, String> nacosMap = new HashMap<>();
//        nacosMap.put("service.vgroupMapping.crm_tx_group", "default");
//        nacosMap.put("service.vgroupMapping.admin_tx_group", "default");
//        nacosMap.put("service.vgroupMapping.examine_tx_group", "default");
//        nacosMap.put("service.vgroupMapping.oa_tx_group", "default");
//        nacosMap.put("service.vgroupMapping.hrm_tx_group", "default");
//        nacosMap.put("service.vgroupMapping.jxc_tx_group", "default");
//        nacosMap.put("store.mode", "db");
//        nacosMap.put("store.db.datasource", "druid");
//        nacosMap.put("store.db.dbType", "mysql");
//        nacosMap.put("store.db.driverClassName", "com.mysql.jdbc.Driver");
//        String host = dataSourceProperties.getUrl().replace("jdbc:mysql://", "").split(":")[0];
//        nacosMap.put("store.db.url", "jdbc:mysql://" + host + ":3306/seata?useUnicode=true");
//        nacosMap.put("store.db.user", dataSourceProperties.getUsername());
//        nacosMap.put("store.db.password", dataSourceProperties.getPassword());
//        nacosMap.put("store.db.minConn", "5");
//        nacosMap.put("store.db.maxConn", "30");
//        nacosMap.put("store.db.globalTable", "global_table");
//        nacosMap.put("store.db.branchTable", "branch_table");
//        nacosMap.put("store.db.queryLimit", "100");
//        nacosMap.put("store.db.lockTable", "lock_table");
//        nacosMap.put("store.db.maxWait", "5000");
//        String group = "SEATA_GROUP";
//        nacosMap.forEach((k, v) -> {
//            try {
//                Properties properties = new Properties();
//                properties.put("serverAddr", serverAddr);
//                ConfigService configService = NacosFactory.createConfigService(properties);
//                boolean isPublishOk = configService.publishConfig(k, group, v);
//                log.warn("seata初始化：{}", isPublishOk);
//            } catch (NacosException e) {
//                log.error("同步seata失败", e);
//            }
//        });
//
//    }

    /**
     * 查询所有员工
     *
     * @return
     */
    @Override
    public List<UserInfo> queryAllUserInfoList() {
        List<AdminUser> adminUserList = lambdaQuery().list();
        List<AdminUserRole> userRoles = adminUserRoleService.query().list();
        Map<Long, List<AdminUserRole>> longListMap = userRoles.stream().collect(Collectors.groupingBy(AdminUserRole::getUserId));
        List<UserInfo> userInfoList = adminUserList.stream().map(user -> BeanUtil.copyProperties(user, UserInfo.class)).collect(Collectors.toList());
        for (UserInfo userInfo : userInfoList) {
            List<AdminUserRole> roleList = longListMap.get(userInfo.getUserId());
            if (roleList == null) {
                roleList = new ArrayList<>();
            }
            userInfo.setRoles(roleList.stream().map(AdminUserRole::getRoleId).collect(Collectors.toList()));
        }
        return userInfoList;
    }

    @Override
    public List<Long> queryChannelSales() {

        return this.baseMapper.queryChannelSales();
    }

    /**
     * 获取营销讲师集合
     * @return
     */
    @Override
    public List<AdminUserVO> queryTeacherList(){
        // 营销讲师Id
        return null;
    }

    /**
     * 获取营销讲师集合
     * @return
     */
    @Override
    public BasePage<AdminUserVO> queryTeacherListForLeads(){
        QueryWrapper<CrmField> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("label", 1);
        queryWrapper.eq("field_name","teacher_id");
        List<CrmField> fieldList = SpringUtils.getBean(ICrmFieldService.class).getBaseMapper().selectList(queryWrapper);
        AdminUserBO adminUserBO = new AdminUserBO();
        adminUserBO.setPageType(0);
        if(CollectionUtil.isNotEmpty(fieldList)){
            CrmField crmField = fieldList.get(0);
            if(crmField.getRestrictType() == null){
                BasePage<AdminUserVO> userBasePage = new BasePage<>();
                userBasePage.setRecords(list().stream().map(adminUser -> {
                    AdminUserVO userVO = BeanUtil.copyProperties(adminUser, AdminUserVO.class);
                    userVO.setDeptName(UserCacheUtil.getDeptName(userVO.getDeptId()));
                    return userVO;
                }).collect(Collectors.toList()));
                return userBasePage;
            }else if(crmField.getRestrictType() == 0 && StringUtils.isNotEmpty(crmField.getRestrictData())){
                JSONObject deptJson = JSON.parseObject(crmField.getRestrictData());
                Integer deptId = deptJson.getInteger("deptId");
                List<Integer> list = adminDeptService.queryChildDept(deptId);
                list.add(adminUserBO.getDeptId());
                adminUserBO.setDeptIdList(list);
                return getBaseMapper().queryUserPage(adminUserBO.parse(), adminUserBO);
            }else if(crmField.getRestrictType() == 1 && StringUtils.isNotEmpty(crmField.getRestrictData())){
                if(StringUtils.isNotEmpty(crmField.getRestrictData().substring(1, crmField.getRestrictData().length() - 1))){
                    String[] split = String.valueOf(crmField.getRestrictData().substring(1, crmField.getRestrictData().length() - 1)).split(",");
                    List<Integer> roleIds = new ArrayList<>();
                    for (String roleId : split){
                        roleIds.add(Integer.valueOf(roleId));
                    }
                    adminUserBO.setRoleIdList(roleIds);
                    return getBaseMapper().queryUserPage(adminUserBO.parse(), adminUserBO);
                }
            }
        }
        // 营销讲师Id
        BasePage<AdminUserVO> userBasePage = new BasePage<>();
        userBasePage.setRecords(list().stream().map(adminUser -> {
            AdminUserVO userVO = BeanUtil.copyProperties(adminUser, AdminUserVO.class);
            userVO.setDeptName(UserCacheUtil.getDeptName(userVO.getDeptId()));
            return userVO;
        }).collect(Collectors.toList()));
        return userBasePage;
    }

    @Override
    public List<Long> queryUserListByRoleIds(long[] ids) {
        return this.baseMapper.queryUserListByRoleIds(ids);
    }

    @Override
    public List<Long> queryUserListByDeptIds(long[] ids) {
        return this.baseMapper.queryUserListByDeptIds(ids);
    }

    public int insertAdminUser(AdminUser adminUser){
        return this.baseMapper.insertAdminUser(adminUser);
    }

    @Override
    public Map<String,Object> getUserAndSeatsInfo(){
        Map<String,Object> result = new HashMap<>();
        result.put("userCount",0);
        result.put("openCount",0);
        result.put("seatsCount",0);
        result.put("allCount",0);
        return  result;
    }

    @Override
    public Map<String, Object> loadOrgExpireReminder() {
        Map<String,Object> result = new HashMap<>();
        result.put("reminder",false);
        result.put("time",null);
//        UserInfo userInfo = UserUtil.getUser();
//        if(Optional.ofNullable(userInfo).isPresent() && Optional.ofNullable(userInfo.getUserId()).isPresent()){
//            Long userId = userInfo.getUserId();
////            BillGroup billGroup = SpringUtils.getBean(BillGroupService.class).queryBillGroup(OrgIdThreadLocal.getOrgId());
//            result.put("time",DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,billGroup.getOpenEndTime()));
//            Date now = DateUtils.getNowDate();
//            Date openEndTime = billGroup.getOpenEndTime();
//            if(now.before(openEndTime)){
//                long count = (openEndTime.getTime() - now.getTime()) / (24 * 60 * 60 * 1000l);
//                if(count >= 0 && count <= 7){
//                    String dateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,now);
//                    String key = Constants.ORG_EXPIRE_REMINDER + OrgIdThreadLocal.getOrgId() +"_"+dateStr;
//                    Long value = redisCache.getCacheMapValue(key,String.valueOf(userId));
//                    if(!Optional.ofNullable(value).isPresent()){
//                        result.put("reminder",true);
//                        redisCache.setCacheMapValue(key,String.valueOf(userId),userId);
//                    }
//                }
//            }
//        }
        return result;
    }

    /**
     * 机构id和用户id缓存
     */
    public void saveUserDeptCache(){
        LambdaQueryWrapper<AdminUser> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(AdminUser::getStatus, 1);
        List<AdminUser> userList = getBaseMapper().selectList(queryWrapper);
        if(!CollectionUtils.isEmpty(userList)){
            redisCache.deleteObject(AdminConst.USER_DEPT_ID_CACHE_);
            Map<Integer, List<AdminUser>> userGroupMap = userList.stream().collect(Collectors.groupingBy(AdminUser::getDeptId, Collectors.toList()));
            for(Integer deptId : userGroupMap.keySet()){
                List<AdminUser> list = userGroupMap.get(deptId);
                if(!CollectionUtils.isEmpty(list)){
                    List<Long> userIds = list.stream().map(AdminUser::getUserId).collect(Collectors.toList());
                    redisCache.setCacheMapValue(AdminConst.USER_DEPT_ID_CACHE_,String.valueOf(deptId),userIds);
                }else{
                    List<Long> userIds = new ArrayList<>();
                    redisCache.setCacheMapValue(AdminConst.USER_DEPT_ID_CACHE_,String.valueOf(deptId),userIds);
                }
            }
        }
    }
}
